package com.chen;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CompletableFutureTimeoutExample {
    public static void main(String[] args) {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟长时间任务
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return 1;
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟较短时间任务
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return 2;
        });

        // 使用 allOf 等待所有任务完成，并设置超时
        try {
            CompletableFuture.allOf(future1, future2).get(3, TimeUnit.SECONDS); // 设置超时时间为3秒
            System.out.println("success:" + future1.get() + future2.get());
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

    }
}
